package ink.metoo.auto.fishpi.chatroom

import ink.metoo.auto.fishpi.Log
import ink.metoo.auto.fishpi.call.ChatRoomCall
import okhttp3.WebSocket
import org.jline.jansi.Ansi
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.text.SimpleDateFormat

object ChatRooms : Runnable {

    private var CRLog: Logger = LoggerFactory.getLogger("ChatRoomLog")

    private var dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    var ws: WebSocket? = null
    var onlineUsers: Set<String> = emptySet()
    var discussing: String? = null

    fun console(message: Message? = null, content: String?) {
        var pContent = ""
        if (message != null) {
            if (!message.oId.isNullOrBlank()) {
                pContent += Ansi().a('[')
                    .fgRed()
                    .a("${message.oId}")
                    .reset()
                    .a(']')
                    .a(' ')
            }
            if (!message.time.isNullOrBlank()) {
                pContent += Ansi()
                    .fgGreen()
                    .a(message.time)
                    .reset()
                    .a(" - ")
            }
            if (!message.userName.isNullOrBlank()) {
                pContent += if (!message.userNickname.isNullOrBlank()) {
                    "${message.userNickname}(${message.userName}) : "
                } else {
                    "${message.userName} : "
                }
            }
        }
        CRLog.info("{}{}", pContent, content)
    }

    fun systemConsole(message: Message? = null, content: String?) {
        val msg = message ?: Message()
        msg.userName = "SYSTEM"
        msg.userNickname = "系统消息"
        if (msg.time.isNullOrBlank()) {
            msg.time = dateFormat.format(System.currentTimeMillis())
        }
        console(msg, content)
    }

    @Synchronized
    override fun run() {
        try {
            println("\u001b[H\u001b[2J")
            ws = ChatRoomCall.watchChatRoom(ChatRoomWebSocketListener())
        } catch (e: Exception) {
            Log.error("watch chatroom fail:" + e.message, e)
            cancel()
        }
    }

    @Synchronized
    fun cancel() {
        ws?.cancel()
        ws = null
        discussing = null
    }

    @Synchronized
    fun refresh() {
        cancel()
        run()
    }

}
